package com.mall.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.entity.sys.RoleEO;
import com.mall.entity.sys.UserEO;
import com.mall.service.sys.IRoleService;
import com.mall.service.sys.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;





@Service
public class UserSecurityServiceImpl implements UserDetailsService {
   @Autowired
   private IUserService userService;
   @Autowired
   private IRoleService roleService;
   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      try {
         UserEO eo = userService.getOne(new QueryWrapper<UserEO>().eq("username", username));
         if (eo == null) {
            throw new UsernameNotFoundException("用户名密码错误！");
         }
         List<RoleEO> roles = roleService.getRolesByUserId(eo.getUserId());
         String strRole = "";
         for(RoleEO r:roles) {
            strRole += r.getRoleCode()+",";
         }
         System.out.println("用户 "+eo.getUsername()+" 拥有角色："+strRole);
         
         List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
       if(!CollectionUtils.isEmpty(roles)) {
    	   for(RoleEO reo : roles) {
    		   String code = reo.getRoleCode();
    		   grantedAuthorities.add(new SimpleGrantedAuthority(code));
    	   }
       }
         
         UserDetailEO detail =  new UserDetailEO(eo);
         detail.setAuthorities(grantedAuthorities);
         
         return detail;
         
      } catch (UsernameNotFoundException e) {
         throw e;
      } catch (Exception e) {
         e.printStackTrace();
         throw new UsernameNotFoundException(e.getMessage());
      }
   }
}
